﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using QRCodeBluetooth.DAL;
using QRCodeBluetooth.Models;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace QRCodeBluetooth.Controllers
{
    [Route("api/[controller]")]
    [ApiExplorerSettings(GroupName = "v1")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private JwtSettings _jwtSettings;
        JwtToken _jwttoken = new JwtToken();
        IHttpContextAccessor _access;
        public LoginController(IOptions<JwtSettings> jwtSettingsAccesser, IHttpContextAccessor access
        )
        {
            _jwtSettings = jwtSettingsAccesser.Value;
            _access = access;
        }

        /// <summary>
        /// 登录
        /// </summary>
        [HttpPost]
        [Route("Login")]
        public ResponseMessage Login(string LoginName, string LoginPwd)
        {
            ResponseMessage message = new ResponseMessage();
            HomeDAL da = new HomeDAL();
            try
            {
                UserInfo user = da.GetUser(LoginName, LoginPwd);
                if (user != null)
                {
                    _access.HttpContext.Session.SetString("UserId", user.id.ToString());
                    _access.HttpContext.Session.SetString("LoginName", LoginName);
                    message = ProcessUser(user);
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "账号或密码不正确";
                }

            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = "登录异常";
                message.data = null;
                message.total = 0;
            }
            return message;
        }

        private ResponseMessage ProcessUser(UserInfo userInfo)
        {
            ResponseMessage message = new ResponseMessage();
            string token = MakeToken(userInfo);
            if (token.Equals(""))
            {
                message.errcode = 1; message.errmsg = "生成Token错误"; message.data = null;
                return message;
            }
            _jwttoken.Token = token;
            userInfo.Token = _jwttoken.Token;
            message.errcode = 0;
            message.errmsg = "";
            message.data = userInfo;
            return message;
        }

        private string MakeToken(UserInfo info)
        {
            string strToken = "";
            var claim = new Claim[]{
                   new Claim(ClaimTypes.Name,info.loginId),
                   new Claim("UserID",info.id.ToString()),
                   new Claim("UserName",info.loginId)
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken
            (
                issuer: _jwtSettings.Issuer,
                audience: _jwtSettings.Audience,
                claims: claim,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddMinutes(118),//过期时间                
                signingCredentials: creds
            );
            try
            {
                strToken = new JwtSecurityTokenHandler().WriteToken(token);
            }
            catch (Exception ee) { return ""; }

            return strToken;
        }
    }
}
